package com.atguigu.tingshu.search.listener;

import com.atguigu.tingshu.search.service.impl.SearchServiceImpl;
import org.redisson.api.RBloomFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.CollectionUtils;

import java.time.Duration;
import java.util.List;

/**
 * Description:
 *
 * @author Yanxinhao on 2025/2/7
 */
public class DistriBloomFilterInitListener implements SpringApplicationRunListener {

    Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 当前的started()方法会在SpringBoot启动的过程中被回调执行两次，
     * 1）springboot加载cloud组件比如nacos. 此时传入来的容器是没有应用的Bean对象，只拥有默认的Bean对象
     * 2）springboot自己启动的过程中来回调， ConfigurableApplicationContext容器才拥有应用的Bean对象
     * @param context
     * @param timeTaken
     */
    @Override
    public void started(ConfigurableApplicationContext context, Duration timeTaken) {
       //1.先判断容器内是否包含布隆过滤器Bean对象
        boolean isContains = context.containsBean("bloomFilter");
        if (isContains){
            //2.获取布隆过滤器Bean对象
            RBloomFilter bloomFilter = context.getBean("bloomFilter", RBloomFilter.class);
            //3.判断当前布隆过滤器是否被初始化过，如果count = 0 则说明没有初始化过，那么我们才进行初始化
            long count = bloomFilter.count();
            if (count == 0){
                //4.获取容器中的SearchServiceImpl Bean对象
                SearchServiceImpl searchServiceImpl = context.getBean("searchServiceImpl", SearchServiceImpl.class);
                List<Long> albumIdList = searchServiceImpl.getAlbumIdList();
                if (!CollectionUtils.isEmpty(albumIdList)){
                    for (Long id : albumIdList) {
                        bloomFilter.add(id);
                    }
                    logger.info("分布式布隆过滤器初始化完毕，内部id数量个数：" + bloomFilter.count());
                }
            }
        }
    }
}